/**
 * 
 */
package com.gopay.bis.cmb.ebank.operation;

import java.io.UnsupportedEncodingException;

import cmb.MerchantCode;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.cmb.ebank.pay.CmbB2cMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ICertHelper;

/**
 * @CmbB2cCerthelper.java
 * @author Ryan
 * @2013-10-30 上午9:23:35 www.gopay.com.cn Inc.All rights reserved.
 */
public class CmbB2cCerthelper implements ICertHelper {

	/**
	 * 招行报文加签
	 */
	public String sign(BaseMessage baseMessage) throws GopayException {
		CmbB2cMessage cmbB2cMessage = (CmbB2cMessage) baseMessage;
		BankLogUtils.printB2CSignPlainLog(baseMessage);
		String strVerifyCode = MerchantCode.genMerchantCode(cmbB2cMessage.getPrivateKeyPath(),
		cmbB2cMessage.getDate(), cmbB2cMessage.getBranchID(),
		cmbB2cMessage.getCoNo(), cmbB2cMessage.getBillNo(),
		cmbB2cMessage.getAmt(), "", cmbB2cMessage.getMerchantUrl(), "",
		"", "", cmbB2cMessage.getGoodsType(), cmbB2cMessage.getReserved());
		BankLogUtils.printB2CSignSignatureLog(baseMessage, strVerifyCode);
		return strVerifyCode;
	}

	/**
	 * 报文验签
	 */
	public Object verify(BaseMessage baseMessage) throws GopayException {

		boolean result = false;
		CmbB2cMessage cmbB2cMessage = (CmbB2cMessage) baseMessage;
		try {
			cmb.netpayment.Security security = new cmb.netpayment.Security(cmbB2cMessage.getPublicKeyPath());
			byte[] signMsg = cmbB2cMessage.getSignature().getBytes("GB2312");
			BankLogUtils.printB2CVerifyPlainLog(cmbB2cMessage);
			result = security.checkInfoFromBank(signMsg);
			BankLogUtils.printB2CVerifySignatureLog(cmbB2cMessage,cmbB2cMessage.getSignMessage());
			BankLogUtils.printB2CVerifyResultLog(cmbB2cMessage, result);

		} catch (UnsupportedEncodingException e) {
			BankLogUtils.printB2CSignExceptionLog(cmbB2cMessage, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6031);
		} catch (Exception e) {
			BankLogUtils.printB2CSignExceptionLog(cmbB2cMessage, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6031);
		}
		return result;
	}

}
